package com.lanou.controller;

import com.lanou.bean.Staff;
import com.lanou.service.StaffService;
import com.lanou.utils.AjaxResult;
import com.lanou.utils.ValidateUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.annotation.Resource;

/**
 * Created by dllo on 18/4/16.
 */
@Controller
public class LoginController {
    @Resource
    StaffService staffService;

    /**
     * 未通过验证跳转到login页面
     *
     * @return
     */
    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @ResponseBody
    @RequestMapping("/loginsubmit")
    public AjaxResult loginsubmit(@RequestParam("loginName") String loginName,
                                  @RequestParam("loginPwd") String loginPwd) {

        //判断输入非空,输入为空返回false
        boolean b1 = ValidateUtil.validateBlankAndNull(loginName);
        boolean b2 = ValidateUtil.validateBlankAndNull(loginPwd);
        if (b1 && b2) {
            AuthenticationToken token = new UsernamePasswordToken(loginName, loginPwd);
            Subject subject = SecurityUtils.getSubject();
            try {
                subject.login(token);
                return AjaxResult.getOK("登陆成功");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
                return AjaxResult.getNO("登录失败");
            }
        } else {
            return AjaxResult.getNO("输入为空");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getlogname")
    public String getName() {
        Subject subject = SecurityUtils.getSubject();
        Staff satff = (Staff) subject.getPrincipal();
        return satff.getLoginName();
    }

    /**
     * 修改密码
     *
     * @param oldPwd
     * @param newPwd
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/changePwd")
    public AjaxResult changePwd(@RequestParam("oldPwd") String oldPwd,
                                @RequestParam("newPwd") String newPwd) {
        return staffService.changePws(oldPwd, newPwd);
    }

}
